import requests  # pip install requests
import json
import base64
import hashlib
import hmac
import time #for nonce

class BitfinexClient(object):
    BASE_URL = "https://api.binance.com"
    KEY=""
    SECRET=""

    def __init__(self, apikey, secretkey):
        self.KEY = apikey
        self.SECRET = secretkey

    def _nonce(self):
        """
        Returns a nonce
        Used in authentication
        """
        return str(int(round(time.time() * 1000)))

    def _headers(self):

        return {
            "X-MBX-APIKEY": self.KEY
        }

    def account_infos(self):
        """
        Fetch active orders
        """
        ff = requests.get(self.BASE_URL + '/api/v1/time', verify=True)
        #print(ff.json())
        path = "/api/v3/account"
        #nonce = self._nonce()
        nonce = str(ff.json()['serverTime'])
        queryString = 'recvWindow=5000&timestamp=' + nonce
        h = hmac.new(self.SECRET.encode(encoding='utf-8'), queryString.encode(encoding='utf-8'), hashlib.sha256)
        signature = h.hexdigest()
        queryString = queryString + '&signature=' + signature
        #print(self.BASE_URL + path)
        #print(nonce)


        headers = self._headers()

        #print(headers)
        #print(rawBody)


        #print("requests.post("+self.BASE_URL + path + ", headers=" + str(headers) + ", data=" + rawBody + ", verify=True)")
        #r = requests.post(self.BASE_URL + path, headers=headers, data=rawBody, verify=True)
        r = requests.get(self.BASE_URL + path + '?' + queryString, headers=headers, verify=True)
        #print(self.BASE_URL + path + '?' + queryString)
        if r.status_code == 200:
          return r.json()
        else:
          print(r.status_code)
          print(r.content)
          return ''


#ff = BitfinexClient().account_infos()
#print('result:')
#print(ff)